package com.hyt.it.ogt.kq.service.bm.command;

import com.hyt.core.constant.CommonConstant;
import com.hyt.it.ogt.kq.common.bm.utils.ExecutorPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @program: it-ogt-bm
 * @description: 这个类用来做CommandLineRunner、DisposableBean的业务，如需用到上面的操作请继承这个类
 * @author: Yang HuanKun
 * @create: 2022-03-17 16:54
 **/
@Slf4j
@Component
public class DestroyBean implements CommandLineRunner, DisposableBean {

    @Override
    public void run(String... args) throws Exception {
        // 启动的时候不需要做什么事情
    }

    @Override
    public void destroy() throws Exception {
    	try {
            ExecutorService executorService = ExecutorPoolUtil.getExecutorService();
            executorService.shutdown();
            // 这里进行等候一定时间给正在执行的任务执行完成
            if (!executorService.awaitTermination(CommonConstant.TWO, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            log.error("global executor executorService close exception", e);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
        	log.error("global executor executorService close exception", e);
		}

        try {
            ThreadPoolTaskExecutor threadPoolTaskExecutor = ExecutorPoolUtil.getPoolTaskExecutor();
            threadPoolTaskExecutor.shutdown();
        } catch (Exception e) {
            log.error("global executor threadPoolTaskExecutor close exception", e);
        }

        log.info("# global executor service destroy ...");
    }
}
